// pages/mine/user/edit_msg.js
// pages/mine/second_page/edit_user_msg.js
var App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userPhoto: '../../../images/mine_default_img.png',
    username: '',
    sex: '',

    date: '请选择',
    index: 0,
    array: [],
    studentPic: '../../../images/upload_pic.png',

    provice: '',
    proviceId: '',
    city: '',
    cityId: '',

    school: '',
    schoolId: '',
    // schoolErrorTip: false,

    house: '',
    houseId: '',
    dormitory: '',
    dormitoryId: '',
    // dormitoryErrorTip: false,

    listShow: false,
    alertList: [],
    tempProvice: {},//选择的省份
    tempCity: {},//选择的城市
    tempSchool: {},
    tempHouse: {},
    tempFloor: {},
    current: 1, //1表示当前显示的是省
    scrollTop: 0,
    showPop: false, //是否显示弹窗
    phone: '请选择',

    stopDate: false,
    stopPhone: false,
    stopName: false,
    stopSchool: false,
    stopHotel: false,
    stopStudetUrl: false,
    hasAllMsg: false,
    wxPhoto: false //是否有默认头像
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var date = new Date();
    var year = date.getFullYear();
    var yearArr = [];
    for (var i = 0; i < 5; i++) {
      yearArr.push(year + '年');
      year--;
    }
    this.setData({
      array: yearArr
    })
    this.getUserInfo();//获取用户信息
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //back
  backLastPage: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  // bind username
  bindUserName: function () {
    if (this.data.username != '' && this.data.stopName) {
      wx.showToast({
        title: '当前信息不可更改哦！',
        icon: 'none'
      })
      return false;
    }
  },
  nameInput: function (e) {
    this.setData({
      nameErrorTip: false,
      username: e.detail.value,
      proviceShow: false
    })
  },
  //学校选择
  onSchoolHandle: function () {
    let that = this;
    if (that.data.stopSchool) {//提交过信息禁止编辑
      wx.showToast({
        title: '当前信息不可更改哦！',
        icon: 'none'
      })
      return false;
    }
    if (that.data.school == '') { //没有选择过
      that.setData({
        listShow: true,
        current: 1,
        tempProvice: {},//选择的省份
        tempCity: {},//选择的城市
        tempSchool: {},
      })
      that.loadProviceData('');
    } else {
      that.setData({
        listShow: true,
        current: 3,
        tempProvice: { id: that.data.proviceId, name: that.data.provice },//选择的省份
        tempCity: { id: that.data.cityId, name: that.data.city },//选择的城市
        tempSchool: { id: that.data.schoolId, name: that.data.school },
      })
      that.loadOtherList(that.data.cityId, '', '');
    }
  },
  //省份搜索
  loadProviceData: function (pId) {
    let that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: App.data.globalAPI + '/search/index/city',
      data: {
        token: wx.getStorageSync('token'),
        pid: pId,
        name: ''
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        const arr = res.data;
        if (arr.error == 0) {
          that.setData({
            alertList: arr.data
          })

        } else {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }
      },
      complete() {
        wx.hideLoading();
      }
    })
  },
  // 宿舍选择
  onHouseHandle: function () {
    if (this.data.stopHotel) {
      wx.showToast({
        title: '当前信息不可更改哦！',
        icon: 'none'
      })
      return false;
    }
    if (this.data.school == '') {
      wx.showToast({
        title: '请先选择学校',
        icon: 'none',
        duration: 800
      })
    } else {
      if (this.data.dormitory == '') {//没有选择过宿舍
        this.setData({
          tempHouse: {},
          tempFloor: {},
          listShow: true,
          current: 4,
          scrollTop: 0
        })
        this.loadOtherList(this.data.cityId, this.data.schoolId, '');
      } else {
        this.setData({
          tempHouse: { id: this.data.houseId, name: this.data.house },
          tempFloor: { id: this.data.dormitoryId, name: this.data.dormitory },
          listShow: true,
          current: 5,
          scrollTop: 0
        })
        this.loadOtherList(this.data.cityId, this.data.schoolId, this.data.houseId);
      }

    }
  },
  //选择信息
  chosedMsg: function (e) {
    let index = this.data.current;
    let value = e.currentTarget.dataset.value;
    let that = this;
    that.setData({
      scrollTop: 0
    })

    switch (index) {
      case 1:
        that.setData({
          tempProvice: value,
          current: 2
        })
        that.loadProviceData(that.data.tempProvice.id);
        break;
      case 2:
        that.setData({
          tempCity: value,
          current: 3
        })
        that.loadOtherList(that.data.tempCity.id, '', '');
        break;
      case 3:
        if (that.data.school != value.name) {
          that.setData({
            house: '',
            houseId: '',
            dormitory: '',
            dormitoryId: '',
          })
        }
        that.setData({
          tempSchool: value,
          provice: that.data.tempProvice.name,
          proviceId: that.data.tempProvice.id,
          city: that.data.tempCity.name,
          cityId: that.data.tempCity.id,
          school: value.name,
          schoolId: value.id,
          listShow: false,
          current: 4,
          alertList: [],
        })
        break;
      case 4:
        that.setData({
          tempHouse: value,
          current: 5
        })
        that.loadOtherList(that.data.cityId, that.data.schoolId, that.data.tempHouse.id);
        break;
      case 5:
        that.setData({
          tempHouse: value,
          house: that.data.tempHouse.name,
          houseId: that.data.tempHouse.id,
          dormitory: that.data.tempHouse.name + '-' + value.name,
          dormitoryId: value.id,
          listShow: false,
        })
        break;
      default:
    }
  },
  //省份选择
  choseProvince: function () {
    this.setData({
      current: 1,
      tempProvice: {},//选择的省份
      tempCity: {},
      tempSchool: {},
      alertList: [],
    })
    this.loadProviceData('');
  },
  //城市选择
  choseCity: function () {
    this.setData({
      current: 2,
      tempCity: {},
      tempSchool: {},
      alertList: [],
    })
    this.loadProviceData(this.data.tempProvice.id);
  },
  // 宿舍选择
  choseHouse: function () {
    this.setData({
      tempHouse: {},
      tempFloor: {},
      listShow: true,
      current: 4
    })
    this.loadOtherList(this.data.cityId, this.data.schoolId, '');
  },
  // date chose
  bindPickerChange: function (e) {
    this.setData({
      dateErrorTip: false,
      index: e.detail.value,
    })
    this.setData({
      date: this.data.array[this.data.index]
    })
  },
  // 上传图片
  uploadImgHandle: function () {
    let that = this;
    if (that.data.stopStudetUrl) {
      wx.showToast({
        title: '当前信息不可更改哦！',
        icon: 'none'
      })
      return false;
    }
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0];
        wx.uploadFile({
          url: App.data.globalAPI + '/box/submit/uploadstudentcard',
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            file: tempFilePaths,
            token: wx.getStorageSync('token')
          },
          success(res) {
            const data = JSON.parse(res.data);
            if (data.error == 0) {
              that.setData({
                studentPic: data.data.url
              })
            } else {
              wx.showToast({
                title: data.msg,
                icon: 'none',
                duration: 800
              })
            }
          }
        })
      }
    })
  },
  // 提交用户信息
  commitUserMsg: function () {
    // console.log(this.data.username, this.data.sex, this.data.provice
    //   , this.data.city, this.data.school, this.data.house
    //   , this.data.dormitory, this.data.date)
    // return false;
    let that = this;
    if (that.data.username == '' && that.data.school == '' && that.data.dormitory == '' && that.data.date == '请选择' && that.data.studentPic == '../../../images/upload_pic.png') {
      wx.showToast({
        title: '未填写任何信息',
        icon: 'none'
      })
    } else{
      if (that.data.username != '' && (that.data.school == '' || that.data.dormitory == '')) {
        wx.showToast({
          title: '请完善学校和宿舍',
          icon: 'none'
        })
      } else if (that.data.username == '' || that.data.phone == '请选择') {
        wx.showToast({
          title: '请填写姓名和手机号',
          icon: 'none'
        })
      }else{
        wx.showModal({
          title: '保存提示',
          content: '信息保存后不可随意修改，请谨慎填写资料',
          success(res) {
            if (res.confirm) {
              that.uploadUserMsg();
            }
          }
        })
      }
    }

  },

  //提交用户信息接口
  uploadUserMsg: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/user/perfect',
      data: {
        token: wx.getStorageSync('token'),
        nickname: that.data.username,
        // phone: that.data.phone,
        // validate_code:'0000',
        province_id: that.data.proviceId,
        city_id: that.data.cityId,
        school_id: that.data.schoolId,
        floor_id: that.data.houseId,
        hostel_id: that.data.dormitoryId,
        enrol_time: that.data.date == '请选择' ? '' : that.data.date.replace('年', ''),
        student_url: that.data.studentPic == '../../../images/upload_pic.png' ? '' : that.data.studentPic
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
        const arr = res.data;
        if (arr.error == 0) {
          wx.showToast({
            title: '保存成功',
          })
          setTimeout(function () {
            wx.navigateBack({
              detal: 1
            })
          }, 600)

          App.getWxUserinfo();

        } else {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }
      }
    })
  },


  // 上传头像
  uploadPhotoHandle: function () {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0];
        wx.uploadFile({
          url: App.data.globalAPI + '/users/user/avatar',
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            file: tempFilePaths,
            token: wx.getStorageSync('token')
          },
          success(arr) {
            const data = JSON.parse(arr.data);
            if (data.error == 0) {
              that.setData({
                wxPhoto: false,
                userPhoto: data.data.url
              })
              let photo = wx.getStorageSync('userInfo');
              photo.userlogo = that.data.userPhoto;
              wx.setStorageSync('userInfo', photo);
            } else {
              wx.showToast({
                title: data.msg,
                icon: 'none',
                duration: 800
              })
            }
          }
        })
      }
    })
  },
  //获取用户信息
  getUserInfo: function () {
    let that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: App.data.globalAPI + '/users/user/info',
      data: {
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          let userMsg = res.data.data;
          let defaultName = userMsg.openid.slice(0, 10);

          that.setData({
            userPhoto: userMsg.userlogo == null ? '../../../images/mine_default_img.png' : userMsg.userlogo,
            username: (userMsg.nickname == defaultName || userMsg.nickname == null || userMsg.nickname == 'null' || userMsg.nickname == userMsg.phone) ? '' : userMsg.nickname,
            school: userMsg.school == null ? '' : userMsg.school,
            dormitory: userMsg.hostel == null ? '' : (userMsg.floor + '-' + userMsg.hostel),

            date: userMsg.enrol_time != null && userMsg.enrol_time != 1970 ? (userMsg.enrol_time + '年') : '请选择',
            studentPic: userMsg.student_url == null ? '../../../images/upload_pic.png' : userMsg.student_url,
            phone: userMsg.phone == '0' ? '请选择' : userMsg.phone
          })

          if (that.data.userPhoto == '../../../images/mine_default_img.png') {
            that.setData({
              wxPhoto: true,
            })
          }

          if (that.data.phone != '请选择') {
            that.setData({
              stopPhone: true
            })
          } else {
            that.setData({
              stopPhone: false
            })
          }
          if (that.data.username != '') {
            that.setData({
              stopName: true
            })
          }
          if (that.data.school != '') {
            that.setData({
              stopSchool: true
            })
          }
          if (that.data.dormitory != '') {
            that.setData({
              stopHotel: true
            })
          }
          if (that.data.date != '请选择') {
            that.setData({
              stopDate: true
            })
          }
          if (that.data.studentPic != '../../../images/upload_pic.png') {
            that.setData({
              stopStudetUrl: true
            })
          }
          if (that.data.phone != '请选择' && that.data.username != '' && that.data.school != '' && that.data.dormitory != '' && that.data.date != '请选择' && that.data.studentPic != '../../../images/upload_pic.png') {
            that.setData({
              hasAllMsg: true
            })
          }

        }
      },
      complete() {
        wx.hideLoading();
      }
    })
  },
  //学校楼宿舍列表
  loadOtherList: function (cityId, sId, fId) {
    let that = this;
    that.setData({
      alertList: []
    })
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: App.data.globalAPI + '/search/index/belong',
      data: {
        token: wx.getStorageSync('token'),
        name: '',
        city_id: cityId,
        school_id: sId,
        floor_id: fId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        const arr = res.data;
        if (arr.error == 0) {
          //sId,fId为空时表示请求的s是学校，fId为空时表示请求的s是楼栋，都不为空是宿舍
          that.setData({
            alertList: arr.data
          })
        } else {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }
      },
      fail() {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      },
      complete() {
        wx.hideLoading();
      }
    })
  },
  onHideAlert: function () {
    this.setData({
      listShow: false
    })
  },

  //手机号授权
  getPhoneNumber: function (e) {
    if (this.data.stopPhone) {
      wx.showToast({
        title: '当前信息不可更改哦！',
        icon: 'none'
      })
    } else {
      if (e.detail.errMsg == 'getPhoneNumber:ok') {//同意手机号授权
        let that = this;
        wx.request({
          url: App.data.globalAPI + '/users/weixin/decrypt',
          data: {
            token: wx.getStorageSync('token'),
            data: e.detail.encryptedData,
            iv: e.detail.iv
          },
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success(res) {
            if (res.data.error == 0) {
              that.setData({
                phone: JSON.parse(res.data.data).phoneNumber,
                stopPhone: true
              })
              that.bindUserPhone();
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 800
              })
            }
          }
        })
      }

    }
  },

  //提交用户手机
  bindUserPhone: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/user/bindphone',
      data: {
        token: wx.getStorageSync('token'),
        phone: that.data.phone,
        validate_code: '0000',
        is_activity: 0
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
        const arr = res.data;
        if (arr.error != 0) {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }

        if (Object.keys(arr.data).length == 0) { //以前没有盒子
          let userInfo = wx.getStorageSync('userInfo');
          userInfo.phone = that.data.phone;
          wx.setStorageSync('userInfo', userInfo);

        } else {
          wx.showToast({
            title: '信息同步成功',
            icon: 'success',
            duration: 1000
          })
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/index/index',
            })
          }, 1000)

        }
      }
    })
  },


})